package cn.lf.service.impl;
import java.util.Date;

import cn.lf.constant.GenderEnum;
import cn.lf.constant.ResponseCodeEnum;
import cn.lf.constant.UserStatusEnum;
import cn.lf.constant.UserTypeEnum;
import cn.lf.dto.system.UserLoginReqDTO;
import cn.lf.dto.system.UserLoginRepDTO;
import cn.lf.entity.SysUser;
import cn.lf.exception.SelfException;
import cn.lf.mapper.SysUserMapper;
import cn.lf.service.ApiSystemService;
import cn.lf.utils.JwtUtils;
import cn.lf.utils.WechatUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author guoyy
 */
@Service
public class ApiSystemServiceImpl implements ApiSystemService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public UserLoginRepDTO login(UserLoginReqDTO params) {

        UserLoginRepDTO result = new UserLoginRepDTO();

        //用户非敏感信息：rawData
        //签名：signature
        JSONObject rawDataJson = JSON.parseObject(params.getRawData());

        //1、接收小程序发送的code
        //2、开发者服务器 登录凭证校验接口 appid+appsecret+code
        JSONObject sessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(params.getCode());

        //3、接收微信接口服务，获取返回的参数
        String openId = sessionKeyOpenId.getString("openid");

        String sessionKey = sessionKeyOpenId.getString("session_key");

        //4、校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData+sessionKey)
        String signature2 = DigestUtils.sha1Hex(params.getRawData()+sessionKey);

        if(!params.getSignature().equals(signature2)){
            throw new SelfException(ResponseCodeEnum.SYS_ERROR.getCode(),"签名校验失败");
        }

        LambdaQueryWrapper<SysUser> userQueryWrapper = new LambdaQueryWrapper<>();

        userQueryWrapper.eq(SysUser::getUserName,openId);

        List<SysUser> loginUserList = sysUserMapper.selectList(userQueryWrapper);

        SysUser loginUser;

        //如果是注册用户自动注册入库
        if (loginUserList.isEmpty()){

            loginUser = new SysUser();
            loginUser.setUserName(openId);
            loginUser.setLastLoginTime(new Date());
            loginUser.setPassword("123456");
            loginUser.setFullName(rawDataJson.getString("nickName"));
            loginUser.setImgUrl(rawDataJson.getString("avatarUrl"));
            loginUser.setStatus(UserStatusEnum.ENABLE.getCode());
            loginUser.setVipLevel(0);
            loginUser.setCreateTime(new Date());
            loginUser.setUpdateTime(new Date());
            loginUser.setCreateByName(rawDataJson.getString("nickName"));
            loginUser.setUpdateByName(rawDataJson.getString("nickName"));
            loginUser.setUserType(UserTypeEnum.USER.getCode());
            //微信返回的性别是0：未知，1：男性，2：女性
            //本系统是0：女性，1男性
            if (Objects.equals(rawDataJson.getString("gender"),"1")){
                loginUser.setGender(rawDataJson.getString("gender"));
            }else if (Objects.equals(rawDataJson.getString("gender"),"2")){
                loginUser.setGender(GenderEnum.FEMALE.getCode());
            }

            sysUserMapper.insert(loginUser);

        }else {

            loginUser = loginUserList.get(0);

            loginUser.setLastLoginTime(new Date());

            sysUserMapper.updateById(loginUser);

        }
        result.setUserId(loginUser.getUserId());
        result.setToken(JwtUtils.sign(loginUser.getUserName()));
        result.setNickName(loginUser.getFullName());
        result.setImgUrl(loginUser.getImgUrl());

        return result;
    }
}
